<?php
/**
 * @Copyright: (C)2021 BJYHYY Inc. All Rights Reserved.
 * @Author: xuzy
 * @Date: 2021/11/15 20:47
 */

namespace App\Http\Controllers;


use App\Model\DeliveryAddress;
use App\Model\Goods;
use App\Model\GoodsSku;
use App\Model\OrderGoods;
use App\Model\Orders;
use App\Model\Users;
use App\Model\UserShopCartTemp;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class XuangouDugController extends Controller
{

    public $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function debug()
    {
        return $this->success('ok');
    }

    public function userLogin()
    {
        $data = $this->request->all();
        if (!isset($data['account'])) {
            return $this->error('请输入账号');
        }
        if (!isset($data['password'])) {
            return $this->error('请输入密码');
        }
        $exist = Users::query()->where('account', $data['account'])
            ->where('password', Users::getPwd($data['password']))->first();
        if (!$exist) {
            return $this->error('账号或密码错误');
        }
        $exist->login_token = Users::getPwd($exist->id);
        $exist->save();
        return $this->success($exist->login_token);
    }


    /**
     * 首页数据
     * @return \Illuminate\Http\JsonResponse
     */
    public function homeData()
    {
        //春节专区商品
        $yGoodsList = Goods::query()->get()->toArray();
        $yuandaShowGoods = [];
        foreach ($yGoodsList as $key => $value) {
            $yuandaShowGoods[] = [
                "goods_id" => $value['id'],
                "name"     => $value['goods_name'],
                "desc"     => $value['desc'],
                "price"    => $value['min_price'],
                "img"      => $this->getImgUrl($value['goods_image'])
            ];
        }
        $data = [
            'banner'  => [
                ['image' => 'http://file.api.umijoy.com/img/2022112012175967.jpeg']
            ],
            'section' => [
                [
                    "id"    => 22,
                    "tag"   => 'live',
                    "title" => '春节专区',
                    "items" =>$yuandaShowGoods
                ],
            ],
            'navList' => [
                [
                    'id'    => 22,
                    'tag'   => 'live',
                    'title' => '春节专区',
                ],
            ]
        ];
        return $this->success($data);
    }

    /**
     * 商品详情
     * @return \Illuminate\Http\JsonResponse
     */
    public function goodsInfo()
    {
        $id = $this->request->get('goods_id');
        $goodsInfo = Goods::query()->where('id', $id)->first();
        $goodsSku = GoodsSku::query()->select('id as sku_id', 'sku_name', 'sku_image', 'price')
            ->where('goods_id', $id)->get()->toArray();
        foreach ($goodsSku as $key=>$value){
            $goodsSku[$key]['sku_image'] = $this->getImgUrl($value['sku_image']);
        }
        $images =  (array) json_decode($goodsInfo['goods_lunbo'],true);
        $showLunbo = [];
        foreach ($images as $key => $value) {
            $showLunbo[] = [
                'image' => $this->getImgUrl($value)
            ];
        }
        $goodsInfo['goods_image'] =  $this->getImgUrl($goodsInfo['goods_image']);
        $goodsInfo['sku'] = $goodsSku;
        $goodsInfo['swipperList'] = $showLunbo;
        $goodsImgDesc = json_decode($goodsInfo['goods_desc_image'], true);
        $imgDesc = [];
        foreach ($goodsImgDesc as $key=>$value){
            $imgDesc[] = ['img'=>$this->getImgUrl($value)];
        }
        $goodsInfo['goods_desc_image'] = $imgDesc;
        return $this->success($goodsInfo);
    }

    public function getUserInfo()
    {
        $user = $this->checkUser();
        if (!$user) {
            return $this->error('用户未登录');
        }
        return $this->success($user);
    }

    public function checkUser()
    {
        $token = $this->request->header('token');
        if (!$token) {
            return null;
        }
        return Users::query()->where('login_token', $token)->first();

    }

    /**
     * 添加购物车
     * @return \Illuminate\Http\JsonResponse
     */
    public function addCart()
    {
        try {
            $user = $this->checkUser();
            $uid = $user['id'] ?? 0;
            $data = $this->request->all();
            $existCart = UserShopCartTemp::query()->where('uid', $uid)->where('sku_id', $data['sku_id'])->first();
            if ($existCart) {
                return $this->error('当前商品已经加入购物车了');
            }
            $skuInfo = GoodsSku::query()->where('id', $data['sku_id'])->first();
            $goodsInfo = Goods::query()->where('id', $skuInfo['goods_id'])->first();
            $addData = [
                'sku_id'      => $data['sku_id'],
                'uid'         => $uid,
                'goods_name'  => $goodsInfo['goods_name'] . '【' . $skuInfo['sku_name'] . '】',
                'goods_image' => $this->getImgUrl($skuInfo['sku_image']),
                'price'       => $skuInfo['price'],
                'buy_num'     => $data['buy_num'],
                'is_select'   => true,
                'created_at'  => date('Y-m-d H:i:s')
            ];
            $cart = new UserShopCartTemp();
            $cart->insert($addData);
            return $this->success();
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }

    }

    /**
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCartInfo()
    {
        $user = $this->checkUser();
        $cartList = UserShopCartTemp::query()->where('uid', $user['id'] ?? 0)->get()->toArray();
        $showData = [];
        foreach ($cartList as $key => $value) {
            $showData[] = [
                "shopId"    => 100,
                "shopName"  => '',
                "goodsId"   => $value['sku_id'],
                "goodsName" => $value['goods_name'],
                "pic"       => $this->getImgUrl($value['goods_image']),
                "price"     => $value['price'],
                "number"    => $value['buy_num']
            ];
        }
        return $this->success($showData);
    }

    public function buySkuInfo()
    {
        $data = $this->request->all();
        $skuInfo = GoodsSku::query()->where('id', $data['sku_ids'])->first();
        $goodsInfo = Goods::query()->where('id', $skuInfo['goods_id'])->first();
        $cartInfo = [
            'shopId'    => 100,
            'shopName'  => '',
            'goodsId'   => $skuInfo['id'],
            'goodsName' => $goodsInfo['goods_name'] . '【' . $skuInfo['sku_name'] . '】',
            'pic'       => $this->getImgUrl($skuInfo['sku_image']),
            'price'     => $skuInfo['price'],
            'number'    => $data['number']
        ];
        return $this->success([$cartInfo]);
    }

    /**
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function buyCartInfo()
    {
        $skuIds = $this->request->get('sku_ids');
        $user = $this->checkUser();
        $cartList = UserShopCartTemp::query()->where('uid', $user['id'])
            ->whereIn('sku_id', explode(',', $skuIds))->get()->toArray();
        $cartInfo = [];
        foreach ($cartList as $key => $value) {
            $cartInfo[] = [
                'shopId'    => 100,
                'shopName'  => '',
                'goodsId'   => $value['sku_id'],
                'goodsName' => $value['goods_name'],
                'pic'       => $value['goods_image'],
                'price'     => $value['price'],
                'number'    => $value['buy_num']
            ];
        }
        return $this->success($cartInfo);
    }


    public function updateCartGoodsNumber()
    {
        $data = $this->request->all();
        $user = $this->checkUser();
        UserShopCartTemp::query()->where('uid', $user['id'])
            ->where('sku_id', $data['goodsId'])
            ->update(['buy_num' => $data['number']]);
        return $this->success();
    }

    public function deleteCartGoods()
    {
        $skuIds = $this->request->input('ids');
        $user = $this->checkUser();
        UserShopCartTemp::query()->where('uid', $user['id'])
            ->whereIn('sku_id', $skuIds)
            ->delete();
        return $this->success();
    }

    /**
     * 创建订单
     * @return \Illuminate\Http\JsonResponse
     */
    public function createOrder()
    {
        $user = $this->checkUser();
        if (!$user) {
            $this->error('请您先登录');
        }
        $data = $this->request->all();
        $skuList = $data['skus'];
        $skuNums = array_column($skuList, 'number', 'goodsId');
        $skuIds = array_keys($skuNums);
        $skuList = GoodsSku::query()->whereIn('id', $skuIds)->get()->toArray();
        $payMoney = 0;
        foreach ($skuList as $key => $value) {
            $payMoney += ($value['price'] * $skuNums[$value['id']]);
        }

        if ($user['balance'] < $payMoney) {
            return $this->error('余额不足');
        }

        if($payMoney < $user['balance']){
            return $this->error('卡内余额请一次性下单使用，不支持分次下单');
        }
        $db = app('db');
        $db->beginTransaction();
        try {
            //扣除用户余额
            $bool = Users::query()->where('id', $user['id'])->decrement('balance', $payMoney);
            if (!$bool) {
                $this->error('余额支付失败！');
            }
            $addressInfo = DeliveryAddress::query()->where('id', $data['address_id'])->first();
            $saveAddressInfo = $addressInfo['address'] . $addressInfo['detailed'];
            //创建订单
            $orderModel = new Orders();
            $orderModel->uid = $user['id'];
            $orderModel->order_sn = 'H' . date('YmdHis') . $user['id'] . rand(1000, 9999);
            $orderModel->address_id = $data['address_id'];
            $orderModel->order_money = $payMoney;
            $orderModel->pay_money = $payMoney;
            $orderModel->order_status = Orders::STATUS_WAIT_DELIVER;
            $orderModel->address_info = $saveAddressInfo;
            $orderModel->delivery_user = $addressInfo['delivery_user'];
            $orderModel->phone = $addressInfo['delivery_phone'];
            $orderModel->deliver_info = json_encode([]);
            if (!$orderModel->save()) {
                return $this->error('订单创建失败！');
            }
            //创建订单商品记录
            $orderSku = [];
            $skuInfoList = GoodsSku::query()->with('goods')->whereIn('id', $skuIds)->get()->toArray();
            $skuInfoById = array_combine(array_column($skuInfoList, 'id'), $skuInfoList);
            foreach ($skuList as $key => $value) {
                $skuInfo = $skuInfoById[$value['id']];
                $orderSku[] = [
                    'order_id'    => $orderModel->id,
                    'uid'=>$user['id'],
                    'sku_id'      => $value['id'],
                    'goods_name'  => $skuInfo['goods']['goods_name'] . ' ' . $value['sku_name'],
                    'goods_image' => $value['sku_image'],
                    'price'       => $value['price'],
                    'buy_num'     => $skuNums[$value['id']],
                    'order_money' => $value['price'] * $skuNums[$value['id']],
                    'pay_money'   => $value['price'] * $skuNums[$value['id']],
                    'created_at'  => date('Y-m-d H:i:s')
                ];
            }
            $orderGoodsModel = new OrderGoods();
            $bool = $orderGoodsModel->insert($orderSku);
            if (!$bool) {
                return $this->error('创建订单失败！');
            }
            //清除相关购物车信息
            UserShopCartTemp::query()->where('uid', $user['id'])->whereIn('sku_id', $skuIds)->delete();
            $db->commit();
            return $this->success($orderModel->toArray());
        } catch (\Exception $e) {
            $db->rollBack();
            return $this->error($e->getMessage());
        }
    }

    /**
     * 订单详情
     * @return \Illuminate\Http\JsonResponse
     */
    public function orderInfo()
    {
        $id = $this->request->get('id');
        $orderInfo = Orders::query()->where('id', $id)->first();
        $addressInfo = DeliveryAddress::query()->where('id', $orderInfo['address_id'])->first();
        $orderInfo['address_info'] = $addressInfo;
        if($orderInfo['deliver_info']){
            $deliverInfo = json_decode($orderInfo['deliver_info'],true);
            $changeData = $deliverInfo['logisticsTraceDetailList']??[];
            foreach ($changeData as $key=>$value){
                $changeData[$key]['time'] = date('Y-m-d H:i:s',($value['time']/1000));
            }
            $deliverInfo['logisticsTraceDetailList'] = $changeData;
            $orderInfo['deliver_info'] = $deliverInfo;
        }else{
            $orderInfo['deliver_info'] = [];
        }

        return $this->success($orderInfo);
    }

    public function orderList()
    {
        $user = $this->checkUser();
        $orderStatus = $this->request->get('order_status', '');
        $orderList = Orders::query()->with('orderGoods')->where('uid', $user['id']);
        if ($orderStatus !== '') {
            $orderList = $orderList->whereIn('order_status', explode(',', $orderStatus));
        }
        $list = $orderList->orderBy('id', 'desc')->get()->toArray();
        //依次更新物流信息,15天以内的下单时间，离上次更新超过两个小时
        foreach ($list as $key=>$value){
            $orderTime = strtotime($value['created_at']);
            $nowTime = time();
            if($value['deliver_sn'] && ($nowTime - $orderTime < 1296000) && ($nowTime - $value['last_query_deliver_time'] > 7200)){  //24*60*60*15=1296000
                $this->doDeliverUpdate($value['id']);
            }
            $list[$key]['deliver_info'] = json_decode($value['deliver_info'],true);
            $orderGoods = $value['order_goods'];
            foreach ($orderGoods as $k=>$val){
                $orderGoods[$k]['goods_image'] = $this->getImgUrl($val['goods_image']);
            }
            $list[$key]['order_goods'] = $orderGoods;
        }
        return $this->success($list);
    }

    /**
     * 收货地址列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function addressList()
    {
        $user = $this->checkUser();
        $addressList = DeliveryAddress::query()->where('uid', $user['id'])->get()->toArray();
        return $this->success($addressList);
    }

    /**
     * 地址详情
     * @return \Illuminate\Http\JsonResponse
     */
    public function addressInfo()
    {
        $id = $this->request->get('id');
        $info = DeliveryAddress::query()->where('id', $id)->first();
        $info['city_ids'] = explode('-',$info['city_ids']);
        return $this->success($info);
    }

    public function updateAddress()
    {
        $data = $this->request->all();
        $model = new DeliveryAddress();
        //收货地址限制成都
        $cityIds = $data['city_ids'];
        if(!isset($cityIds[0]) || !isset($cityIds[1])){
            return $this->error('请选择您的收货区域！');
        }
        if($cityIds[0] != 510000){
            return $this->error('非常抱歉！目前系统收货地址仅支持四川');
        }
        if (isset($data['id']) && $data['id']) {
            $info = $model->where('id', $data['id'])->first();
            $info->delivery_user = $data['delivery_user'];
            $info->phone = $data['phone'];
            $info->detailed = $data['detailed'];
            $info->address = $data['address'];
            $info->city_ids = join('-',$data['city_ids']);
            $info->save();
        } else {
            $user = $this->checkUser();
            $model->uid = $user['id'];
            $model->delivery_user = $data['delivery_user'];
            $model->phone = $data['phone'];
            $model->detailed = $data['detailed'];
            $model->address = $data['address'];
            $model->city_ids = join('-',$data['city_ids']);
            $model->save();
        }

        return $this->success();
    }

    public function buildAccount()
    {
        $keyPwd = $this->request->get('key_pwd','');
        if($keyPwd !== 'xuzy666'){
           return $this->error('无效的请求！');
        }
        $begin = 200000;
        for ($i=0;$i<385;$i++){
            $password = '';
            $existAccount = Users::query()->where('account',$begin)->first();
            if($existAccount){
                var_dump('账号：【'.$begin.'】存在，跳过');
            }
            for ($j=0;$j<6;$j++){
                $isWord = rand(0,1);
                if($isWord){
                    $password.=$this->getRandWord();
                }else{
                    $password.=$this->getRandNumber();
                }
            }
            $user = new Users();
            $user->company_id = 1;
            $user->account = $begin++;
            $user->balance = 600;
            $user->password = Users::getPwd($password);
            $user->initial_password = $password;
            $user->save();
            var_dump('创建账号：【'.$begin.'】成功');
            echo '<br/>';
           usleep(100);
        }
    }

    private function getRandNumber()
    {
        $randList = [2,3,4,5,6,7,8,9];
        return $randList[rand(0,7)];
    }

    private function getRandWord()
    {
        $words = ['a','b','c','d','e','f','g','h','j','k','m','n','p','q',
            'r','s','t','u','v','w','x','v'];
        //        $numWords = [1,2,3,4,5,6,7,8,9];
//        //随机大写
//        $randNum = $numWords[rand(0,9)];
//        if($randNum){
//            $word = strtoupper($word);
//        }
        return $words[rand(0,21)];
    }

    public function queryDeliverInfo($deliverSn)
    {
        $host = "https://slypass3.market.alicloudapi.com";
        $path = "/express3";
        $method = "GET";
        $appcode = "4d540e5f243d469eb845bb1d38ebe6a3";//开通服务后 买家中心-查看AppCode
        $headers = array();
        array_push($headers, "Authorization:APPCODE  " . $appcode);
        $querys = "number=$deliverSn";  //参数写在这里
        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $out_put = curl_exec($curl);

        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        list($header, $body) = explode("\r\n\r\n", $out_put, 2);
        if ($httpCode == 200) {
            $body = json_decode($body,true);
            return $body['data']['info'][0];
        } else {
            return false;
        }
    }


    public function doDeliverUpdate($orderId)
    {
        try{
            $orderInfo = Orders::query()->where('id',$orderId)->first();
            if(!$orderInfo){
                return;
            }
            //获取物流信息
            $deliverInfo = $this->queryDeliverInfo($orderInfo['deliver_sn']);
            if($deliverInfo){
                $orderInfo->deliver_info = json_encode($deliverInfo,JSON_UNESCAPED_UNICODE);
                $orderInfo->last_query_deliver_time = time();
                $orderInfo->save();
            }
            return;
        }catch (\Exception $e){

        }


    }





}
